<template>
  <div>
    <el-dialog
      v-loading.lock="loading"
      class="base-dialog"
      :custom-class="'panna-dialog_big'"
      :append-to-body="true"
      title="新增记录"
      align="left"
      :visible.sync="innerDialogFormVisible"
      :before-close="handleClose"
    >
      <el-form
        ref="formData"
        class="base-pipeline-layout system-user-form"
        label-width="100px"
        :model="formData"
        :rules="formDataRules"
        status-icon
      >
        <el-form-item
          label="记录编号"
          :label-width="formLabelWidth"
          prop="num"
          :error="errorMsg.num"
        >
          <el-input v-model="formData.num" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item
          label="记录人"
          :label-width="formLabelWidth"
          prop="recordPersonId"
          :error="errorMsg.recordPersonId"
        >
          <el-select
            v-model="formData.recordPersonId"
            placeholder="请选择"
            filterable
            remote
            reserve-keyword
            :remote-method="remoteUser"
          >
            <el-option
              v-for="item in userList"
              :key="item.id"
              :label="item.name"
              :value="item.id"
            >
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item
          label="清洗日期"
          :label-width="formLabelWidth"
          prop="cleaningDate"
          :error="errorMsg.cleaningDate"
        >
          <el-date-picker
            v-model="formData.cleaningDate"
            type="date"
            placeholder="清洗日期"
            format="yyyy-MM-dd"
            value-format="yyyy-MM-dd"
          ></el-date-picker>
        </el-form-item>
        <el-form-item
          label="气袋列表"
          :label-width="formLabelWidth"
          style="width: 100%"
        >
          <el-button type="primary" @click="addAirBagList">添 加</el-button>
          <el-table :data="formData.airBagList" border style="width: 100%">
            <el-table-column align="center" prop="num" label="气袋编号">
              <template #header>
                <span style="color: red">*</span>
                <span>气袋编号</span>
              </template>
              <template slot-scope="scope">
                <el-input v-model="scope.row.num" autocomplete="off"></el-input
              ></template>
            </el-table-column>
            <el-table-column
              align="center"
              prop="cleaningCount"
              label="清洗次数"
              width="120"
            >
              <template #header>
                <span style="color: red">*</span>
                <span>清洗次数</span>
              </template>
              <template slot-scope="scope">
                <el-input
                  v-model="scope.row.cleaningCount"
                  autocomplete="off"
                  :validate-event="false"
                  @blur="handleInputBlur(scope.row)"
                ></el-input
              ></template>
            </el-table-column>
            <el-table-column
              align="center"
              prop="detectionState"
              label="是否检测"
              width="120"
            >
              <template #header>
                <span style="color: red">*</span>
                <span>是否检测</span>
              </template>
              <template slot-scope="scope">
                <el-select
                  v-model="scope.row.detectionState"
                  placeholder="请选择"
                  remote
                  reserve-keyword
                >
                  <el-option
                    v-for="item in detectionStateList"
                    :key="item.value"
                    :label="item.name"
                    :value="item.value"
                  >
                  </el-option>
                </el-select>
              </template>
            </el-table-column>
            <el-table-column align="center" label="备注">
              <template slot-scope="scope">
                <el-input
                  v-model="scope.row.remark"
                  autocomplete="off"
                ></el-input
              ></template>
            </el-table-column>
            <el-table-column align="center" label="操作" width="100">
              <template slot-scope="scope">
                <div class="base-table-operation">
                  <el-link
                    size="mini"
                    type="danger"
                    @click="handleDelete(scope.$index)"
                    >删除</el-link
                  >
                </div>
              </template>
            </el-table-column>
          </el-table>
        </el-form-item>
        <el-form-item
          label="上传图片"
          :label-width="formLabelWidth"
          style="width: 100%"
        >
          <BaseMultipleUpload
            key="BaseUpload"
            ref="BaseUpload"
            v-model="formData.imgArray"
            business-type="110"
            :is-public-file="isPublicFile"
            :file-size="5120"
            :limit="10"
            :style-c-s-s="styleCSS"
            :multiple="true"
            :show-file-list="true"
            :list-type="'picture-card'"
            style="
              display: flex;
              align-items: start;
              padding-left: 10px;
              flex-direction: column;
            "
            :tip="'请上传大小在5M以内,格式在jpg,jpeg,png的图片,最多上传10张图片'"
            :accept="'.jpeg,.jpg,.png,.gif,.bmp,.tiff'"
          />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer" align="center">
        <el-button type="primary" @click="onSubmit('formData')"
          >保 存</el-button
        >
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {
  create,
  update,
  get,
  GetAirBagCleaningRecordNum,
} from "../../../api/Material/MaterialAirBagCleaningRecord.js";
import {getUserListNoPage} from "@/ModulePermission/api/Permission/PermissionUser.js"
import { GetPublicStaticImgInfo } from "@/api/Base";
import { formatTime } from "../../../utils/time";
import _ from "lodash";
export default {
  name: "MaterialAirBagCleaningRecordEdit",
  props: {
    id: {
      type: String,
      default: "",
    },
    dialogFormVisible: {
      type: Boolean,
      default: false,
    },
  },
  data() {
    return {
      loading: false,
      isPublicFile: false,
      innerDialogFormVisible: false,
      formatTime,
      generateNum: "",
      formLabelWidth: "100px",
      styleCSS: "text-align:left",
      userList: [],
      detectionStateList: [
        { value: 0, name: "否" },
        { value: 1, name: "是" },
      ],
      initData: {
        id: 0,
        num: "",
        recordPersonId: 0,
        cleaningDate: null,
      },
      formData: {
        id: 0,
        num: "",
        recordPersonId: null,
        cleaningDate: null,
        airBagList: [],
        imgArray: [],
        // true系统生成的编号
        generateNumState: true,
      },
      formDataRules: {
        num: [
          {
            required: true,
            trigger: "blur",
            validator: this.Helper.validateFunction,
          },
        ],
        recordPersonId: [
          {
            required: true,
            trigger: "blur",
            validator: this.Helper.validateFunction,
          },
        ],
        cleaningDate: [
          {
            required: true,
            trigger: "blur",
            validator: this.Helper.validateFunction,
          },
        ],
      },
      initErrorMsg: {
        num: "",
        recordPersonId: "",
        cleaningDate: "",
      },
      errorMsg: {
        num: "",
        recordPersonId: "",
        cleaningDate: "",
      },
    };
  },
  watch: {
    innerDialogFormVisible(val) {
      this.$emit("update:dialogFormVisible", val);
    },
  },
  created() {
    this.innerDialogFormVisible = this.dialogFormVisible;
    this.init();
  },
  methods: {
    init() {
      this.getPermissionUser();
      if (this.id) {
        this.loading = true;
        get({ id: this.id })
          .then((res) => {
            const promises = res.data.imgArray.map((item) => {
              return GetPublicStaticImgInfo({
                file: item.filePath,
                isPublicFile: this.isPublicFile,
              }).then((res) => {
                item.url = res.data;
                item.name = item.originalFileName;
              });
            });
            Promise.all(promises).then(() => {
              this.formData = res.data;
              this.loading = false;
            });
          })
          .catch(() => {
            this.loading = false;
          });
      } else {
        this.formData.cleaningDate = formatTime(new Date());

        GetAirBagCleaningRecordNum({}).then((res) => {
          this.formData.num = res.data;
          this.generateNum = res.data;
        });
      }
    },
    handleDelete(index) {
      this.formData.airBagList.splice(index, 1);
    },
    handleInputBlur(row) {
      // 正则表达式：必须为正整数
      const reg = /^[1-9]\d*$/;
      if (!reg.test(row.cleaningCount)) {
        this.$message.error("请输入大于等于0的正整数");
        row.cleaningCount = 1; // 重置为默认值
      }
    },
    // 添加气袋列表
    addAirBagList() {
      this.formData.airBagList.push({});
    },
    remoteUser(query) {
      this.getPermissionUser(query);
    },
    getPermissionUser(name) {
      var data = { name: null, userStatus: 1 };

      if (name) {
        data.name = name;
      }
      getUserListNoPage(data)
        .then((res) => {
          this.userList = res.data;
        });
    },
    // 关闭弹框
    handleClose() {
      this.closeDialog();
    },
    cancel() {
      this.innerDialogFormVisible = false;
      this.$emit("close");
    },
    closeDialog() {
      this.cancel();
    },
    onSubmit: _.throttle(function() {
      if (this.formData.num !== this.generateNum) {
        this.formData.generateNumState = false;
      }

      if (
        this.formData.airBagList === undefined ||
        this.formData.airBagList === null ||
        this.formData.airBagList.length === 0
      ) {
        this.$message.error("气袋列表不能为空");
        return false;
      }

      for (let i = 0; i < this.formData.airBagList.length; i++) {
        if (!this.formData.airBagList[i].num) {
          this.$message.error("气袋编号不能为空");
          return false;
        }
        if (!this.formData.airBagList[i].cleaningCount) {
          this.$message.error("清洗次数不能为空");
          return false;
        }
        if (
          this.formData.airBagList[i].detectionState !== 0 &&
          this.formData.airBagList[i].detectionState !== 1
        ) {
          this.$message.error("请选择是否检测");
          return false;
        }
      }

      this.$refs.formData.validate((valid) => {
        if (valid) {
          this.loading = true;
          this.errorMsg = this.Helper.deepCopy(this.initErrorMsg);
          if (this.formData.id <= 0) {
            create(this.formData)
              .then((res) => {
                if (res.code === 200) {
                  this.closeDialog();
                } else {
                  this.showValidateMsgCheck(res);
                }
                this.loading = false;
              })
              .catch(() => {
                this.loading = false;
              });
          } else {
            update(this.formData)
              .then((res) => {
                if (res.code === 200) {
                  this.closeDialog();
                } else {
                  this.showValidateMsgCheck(res);
                }
                this.loading = false;
              })
              .catch(() => {
                this.loading = false;
              });
          }
        } else {
          return false;
        }
      });
    }, 5000),
    showValidateMsgCheck(res) {
      if (res.msg) {
        this.Helper.showValidateMsg("num", this.errorMsg, res.msg);
        this.Helper.showValidateMsg("recordPersonId", this.errorMsg, res.msg);
        this.Helper.showValidateMsg("cleaningDate", this.errorMsg, res.msg);
      }
    },
  },
};
</script>
